import Vue from 'vue'
import Vuex from 'vuex'
import env from '../common/http/env'
import apiUrl from '../common/api/'


function qsParse(url) {
	if (!url.includes("?")) {
		return {};
	}
	let arr1 = url.split("?");
	let params = arr1[1].split("&");
	let obj = {}; //声明对象
	for (let i = 0; i < params.length; i++) {
		let param = params[i].split("=");
		obj[param[0]] = param[1].split("#/")[0]; //为对象赋值
	}
	return obj;
};

Vue.use(Vuex)

const store = new Vuex.Store({
	state: {
		hasLogin: false,
		loginProvider: "",
		openid: null,
		isCanUse: true
	},
	mutations: {
		/* login(state, provider) {
			state.hasLogin = true;
			state.loginProvider = provider;
		}, */
		logout(state) {
			state.hasLogin = false
			state.openid = null
		},
		setOpenid(state, openid) {
			state.openid = openid
			state.hasLogin = true;
			/*注入用户openid*/
			uni.setStorage({
				key: 'storage_key',
				data: openid,
				success: function() {
					console.log('success');
				}
			});
		},
		setIsCanUse(state) {
			state.isCanUse = false
		},
		loginH5(state) {
			console.log("公众号网页授权登陆方式");
			let qsobj = qsParse(window.location.href);
			if (qsobj.openid) {
				store.commit('setOpenid', qsobj.openid);
			} else {
				if (!qsobj.openid) {
					console.log("微信重新授权");
					// 微信授权,开发阶段暂时注释掉代码
					debugger;
					window.location.href = "http://api.51self-service.cn/wx/authorize?returnUrl=" +
						encodeURIComponent(window.location.href);
				}
			}
		},
		//第一授权获取用户信息===》按钮触发
		wxGetUserInfo(state) {
			let _this = this;
			uni.getUserInfo({
				provider: 'weixin',
				success: function(infoRes) {
					uni.setStorageSync('isCanUse', false); //记录是否第一次授权  false:表示不是第一次授权
					store.commit('setIsCanUse', false);
					console.log("--------wxGetUserInfo--------");
					console.log(infoRes);
					let nickName = infoRes.userInfo.nickName; //昵称
					let avatarUrl = infoRes.userInfo.avatarUrl; //头像
					try {
						// _this.updateUserInfo();
					} catch (e) {}
				},
				fail(res) {
					console.log("------wxGetUserInfo fail------");
				}
			});
		},

		//登录
		login(state) {
			let _this = this;
			uni.showLoading({
				title: '登录中...'
			});

			// 1.wx获取登录用户code
			uni.login({
				provider: 'weixin',
				success: function(loginRes) {
					let code = loginRes.code;
					if (!_this.isCanUse) {
						//非第一次授权获取用户信息
						uni.getUserInfo({
							provider: 'weixin',
							success: function(infoRes) {
								uni.setStorageSync('isCanUse', false); //记录是否第一次授权  false:表示不是第一次授权
								store.commit('setIsCanUse', false);
								console.log(infoRes);
								//获取用户信息后向调用信息更新方法
								let nickName = infoRes.userInfo.nickName; //昵称
								let avatarUrl = infoRes.userInfo.avatarUrl; //头像
								// _this.updateUserInfo(); //调用更新信息方法
							}
						});
					}

					console.log("code: " + code);

					//2.将用户登录code传递到后台置换用户SessionKey、OpenId等信息
					uni.request({
						// url: env.baseURL + apiUrl.POST_MP_UserId,
						url: "https://api.51self-service.cn/wx/getMpUserInfo",
						data: {
							code: code,
							type: ""
						},
						method: 'POST',
						header: {
							'content-type': 'application/json'
						},
						success: (res) => {
							//openId、或SessionKdy存储//隐藏loading
							console.log(res);
							if (res.statusCode === 200 && res.data.code === 1200) {
								store.commit('setOpenid', res.data.msg);
								state.hasLogin = true;
								uni.hideLoading();
							}else{
								store.commit('login');								
							}

						}
					});
				},
			});
		},
		//向后台更新信息
		updateUserInfo(state) {
			let _this = this;
			uni.request({
				url: 'url', //服务器端地址
				data: {
					appKey: this.$store.state.appKey,
					customerId: _this.customerId,
					nickName: _this.nickName,
					headUrl: _this.avatarUrl
				},
				method: 'POST',
				header: {
					'content-type': 'application/json'
				},
				success: (res) => {
					if (res.data.state == "success") {
						uni.reLaunch({ //信息更新成功后跳转到小程序首页
							url: '/pages/index/index'
						});
					}
				}

			});
		}
	},
	getters: {
		openid(state) {
			return state.openid;
		},
		hasLogin(state) {
			return state.hasLogin;
		},
		isCanUse(state) {
			return state.isCanUse;
		}
	},
	actions: {
		// lazy loading openid
		/* getUserOpenId: async function({
			commit,
			state
		}) {
			return await new Promise((resolve, reject) => {
				if (state.openid) {
					resolve(state.openid)
				} else {
					uni.login({
						success: (data) => {
							commit('login')
							setTimeout(function() { //模拟异步请求服务器获取 openid
								const openid = '123456789'
								console.log('uni.request mock openid[' + openid + ']');
								commit('setOpenid', openid)
								resolve(openid)
							}, 1000)
						},
						fail: (err) => {
							console.log('uni.login 接口调用失败，将无法正常使用开放接口等服务', err)
							reject(err)
						}
					})
				}
			})
		} */
	}
})

export default store
